package com.wlhse.service.impl;

import com.wlhse.dao.ProblemFactorDao;
import com.wlhse.dto.TreeDto;
import com.wlhse.entity.ProblemFactorPojo;
import com.wlhse.exception.WLHSException;
import com.wlhse.service.ProblemFactorService;
import com.wlhse.util.*;
import com.wlhse.util.state_code.CodeDict;
import com.wlhse.util.state_code.NR;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;


@Service
public class ProblemFactorServiceImpl implements ProblemFactorService {

    @Resource
    private ProblemFactorDao dao;

    @Resource
    private TreeUtil treeUtil;

    @Resource
    private SortCodeUtil sortCodeUtil;

    @Resource
    private DefaultUtil defaultUtil;

    @Override
    @Transactional
    public String updateProblemFactor(ProblemFactorPojo pojo) {
        String hashString = HashUtil.hash(pojo.getProblemFactorCode() + pojo.getProblemFactorName());
        pojo.setProblemFactorHash(hashString);
        if (dao.updateProblemFactorPojo(pojo) <= 0)
            throw new WLHSException("更新失败");
        return NR.r();
    }

    @Override
    @Transactional
    public String removeProblemFactor(String nodeCode) {
        if (dao.deleteProblemFactorPojo(nodeCode) <= 0)
            throw new WLHSException("删除失败");
        return NR.r();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveProblemFactor(ProblemFactorPojo pojo) {
        if (StringUtils.isNotBlank(pojo.getProblemFactorName())) {
            //应该去pojo复写hashcode方法
            String hash = HashUtil.hash(pojo.getProblemFactorCode() + pojo.getProblemFactorName());
            pojo.setProblemFactorHash(hash);
            String code = pojo.getProblemFactorCode();
            String maxCodeString;
            if (StringUtils.isNotBlank(code)) {
                String maxString = dao.getMaxString(code, 4, 6);
                if (StringUtils.isNotBlank(maxString)) {
                    maxCodeString = sortCodeUtil.getMaxCodeString(maxString);
                } else {
                    maxCodeString = code + "01";
                }
            } else {
                String maxString = dao.getMaxString("", 0, 4);
                if (StringUtils.isNotBlank(maxString)) {
                    maxCodeString = sortCodeUtil.getMaxCodeString(maxString);
                } else {
                    maxCodeString = "0001";
                }
                defaultUtil.setProblemFactor(maxCodeString);
            }
            pojo.setProblemFactorCode(maxCodeString);
            if (dao.insertSingle(pojo) <= 0)
                throw new WLHSException("新增失败");
        }
        return NR.r();
    }

    @Override
    public String getProblemFactorTree() {
        return NR.r(treeUtil.getProblemFactorTree(dao.queryProblemFactor()));
    }
}
